#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2014年9月18日

@author: chenyongbing
'''
import datetime
import sys
import os
from identifyRole import IdentifyRole

import xlrd
from xlutils.copy import copy
    
import xlwt
from localConfig import LocalConfig


myLocalConfig = LocalConfig()



import logging

sys.path.append('../')
from base.zhimind_datas import myZhimindDatas
from base.retail_datas import myRetailDatas

class RunIdentifyByGroup(IdentifyRole):
   
    def get_slist_between_st_et(self,st,et):
        u'''获取2个时间间的所有日期'''
        dlist = []
        count = 0
        nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(-1)).strftime('%Y-%m-%d')
        while nday < et:
            nday = (datetime.date(int(st[:4]),int(st[5:7]),int(st[8:]))+ datetime.timedelta(count)).strftime('%Y-%m-%d')
            count+=1
            dlist.append(nday)
        return dlist
    
    
    
    def stat_customer_by_hour(self,st='',et='',min_rssi=-90,max_rssi=0,walkbyList=[60,120],comp='',groupsInfo=[],show='customer',type='stat',order='time',showTypeList=['day','hour'],opening=None):
        #print st,et,min_rssi,max_rssi,walkby,comp,groups,show,type,order,showTypeList,opening
        rawdir = myLocalConfig.rawdata_path
        spath = myLocalConfig.employee_path
        rssiList = range(min_rssi,max_rssi,2) + [max_rssi]
        #print 'rssiList',rssiList
        rssiMsgList = []
        logging.info('start stat_customer_by_hour')
        for groupMsg in groupsInfo:
            #print groupMsg
            
            devices = groupMsg['devices']
            group = groupMsg['group']
            
            logging.info('start to stat group %s '%(group))
            if groupMsg.has_key('opening'):
                opening = groupMsg['opening']
            else:
                if opening==None:
                    opening = {'opening_weekday':myLocalConfig.opening_weekday,
                               'opening_weekend':myLocalConfig.opening_weekend}
                
    
            days = self.get_slist_between_st_et(st,et)
            groupMsg['data'] = {}
            for day in days:
                logging.info('start: '+group+' ' +day)
                groupMsg['data'][day] = {}
                nextday = (datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10])) + datetime.timedelta(1)).strftime('%Y-%m-%d')
                rawname = 'rawdata.%s.txt'%(day)
                rawfile = rawdir+'/'+rawname
                #print group,day,rawfile
                #if not os.path.exists(rawfile):continue
                if datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10])).weekday not in (0,6):
                    opening_d = opening['opening_weekday']
                else:
                    opening_d =opening['opening_weekend'] 
                
                #myIdentifyRole = IdentifyRole(show=show,order = order,type=type,opening=opening_d,task_name=self.task_name)
                
                self.show = show
                self.order = order 
                self.type = type
                self.opening = opening_d
#                 if not os.path.exists(spath+'/mac_employee.%s.sql'%nextday):
#                     if os.path.exists(spath+'/mac_employee.%s.sql.gz'%nextday):
#                         os.popen('gunzip -c %s > %s'%(spath+'/mac_employee.%s.sql.gz'%nextday,spath+'/mac_employee.%s.sql'%nextday))
#                     if not os.path.exists(spath+'/mac_employee.%s.sql'%nextday):
#                         logging.error('Employee File %s Not Exists.'%(spath+'/mac_employee.%s.sql'%nextday))
#                         #sys.exit()
#                 if os.path.exists(spath+'/mac_employee.%s.sql'%nextday):
#                     self.EMPLOYEES = self.getEmployeeFromSQL(spath, day)
#                 else:pass

                
                comp_group = myRetailDatas.get_comp_group( shop_group=group)
                
                self.EMPLOYEES=myZhimindDatas.get_employees( group=comp_group,mtype=1)
                if self.nosysemployee == False:
                    self.EMPLOYEES += myZhimindDatas.get_employees( group=group,day=day)
                
                #myIdentifyRole.EMPLOYEES = myIdentifyRole.getEmployeeFromSQL(spath, day)
                #macsDict= myIdentifyRole.filter_by_rssi(rawfile=rawfile, min=min_rssi,devices=devices,group=group)
                macsDict= self.filter_by_rssi(rawfile=rawfile, min=min_rssi,devices=devices,group=group)
#                 print 'macsDict length %s'%len(macsDict)
                logging.info('macsDict length %s'%len(macsDict))
                
                logging.info('start: '+group+' ' +day+' '+str(min_rssi) + ' macDict lens :%s'%len(macsDict))

                groupMsg['data'][day] = self.identify_role_by_dur_with_walkby_list(macsDict, walkbyList=walkbyList, rssiList=rssiList)
                
#                 for rssi in rssiList:
#                     groupMsg['data'][day][rssi] = {}
#                     #logging.info('start: '+group+' ' +day+' '+str(rssi))
#                     #hourMsgs = myIdentifyRole.identify_role_by_dur(macsDict,walkby=walkby,min_rssi=rssi)
#                     for walkby in walkbyList:
#                         hourMsgs = self.identify_role_by_dur(macsDict,walkby=int(walkby),min_rssi=rssi)
#                     
#                         logging.info('Group: '+group+' Day:' +day+' RSSI:'+str(rssi) + ' hourMsgs lens :%s'%len(hourMsgs))
#                         #print rawfile,rssi,devices,group,walkby,hourMsgs
#                         groupMsg['data'][day][rssi][walkby] =   hourMsgs
                #del macsDict
            rssiMsgList.append(groupMsg)
            #del groupMsg
        return rssiMsgList
    
    

             
             
             
             
             
             
             
             
             
             
             
             
             
                
                        
            
    
    def export_to_excel(self,rssiMsgList,workBook=None,xfile='../report/店铺数据核对_testing.xls',min_rssi=-90,max_rssi=0,walkby=60,showTypeList=['day','hour'],show='customer'):
        if show=='customer':
            showName = u'入店人数'
        elif show == 'all':
            showName = u'客流人数'
        if workBook==None:
            if os.path.exists(xfile):
                rb = xlrd.open_workbook(xfile)
                wb = copy(rb)
                sheet_names = rb.sheet_names()
            else:
                wb = xlwt.Workbook()
                sheet_names = []
        else:
            sheet_names = []
            wb = workBook
            
        #wb = xlwt.Workbook()
        rssiList = range(min_rssi,max_rssi,2) + [max_rssi]
        rssiList.reverse()
        for showType in showTypeList:
            if showType=='day':
                rawList = [u'日期',u'客户参考值'] + rssiList
            elif showType=='hour':
                rawList = [u'日期',u'小时',u'客户参考值'] + rssiList
            for  groupMsgList in rssiMsgList:
                
                group = groupMsgList['group']
                
                name = groupMsgList['name']
                days = groupMsgList['data'].keys()
                days.sort()
                if showType=='day':
                    
                    sheet_name = u'%s_%s_%smin_date'%(showName,name,walkby/60)
                    
                elif showType == 'hour':
                    sheet_name = u'%s_%s_%smin_hour'%(showName,name,walkby/60)
                if sheet_name in sheet_names:
                    ws = wb.get_sheet(sheet_names.index(sheet_name))
                else:
                    ws = wb.add_sheet(sheet_name)  
                nrow = len(ws.get_rows())
                if nrow!=0:nrow+=5
                style = xlwt.easyxf('pattern: pattern solid ,fore_colour pale_blue')
                if show == 'customer':
                    ws.write_merge(nrow+0,nrow+0,0,len(rawList)-1,label=u'入店人数(店铺名称：%s    统计时间：%s至%s    db范围%s - %sdb    入店时长标准:%s sec)'%(name,days[0],days[-1],min_rssi,max_rssi,walkby),style=style)
                elif show == 'all':
                    ws.write_merge(nrow+0,nrow+0,0,len(rawList)-1,label=u'客流人数(店铺名称：%s    统计时间：%s至%s    db范围%s - %sdb)'%(name,days[0],days[-1],min_rssi,max_rssi),style=style)
                for x in range(len(rawList)):
                    ws.write(nrow+1,x,rawList[x])
                i = nrow+2
                
                
                #print 'days:',days
                for day in days:
                    
                    ws.write(i,0,day)
                    if showType=='hour':
                        for h in range(24):
                            
                            ws.write(i+h,1,"%s:00:00 - %s:00:00"%(h,h+1))
                        incr = 24
                    else:
                        incr = 0
                    dayMsgList = groupMsgList['data'][day]
                    rssiList2 = dayMsgList.keys()
                    rssiList2.sort()
                    #print dayMsgList
                    j=len(rawList)
                    for rssi in rssiList2:
                        j-=1
                        
                        groupMsg = dayMsgList[rssi]
                        total = 0
                        
                        if showType=='day':
                            
                            for hour,hourMsg in groupMsg.iteritems():
                                total+=len(hourMsg)
                            ws.write(i,j,total)
                            
                        elif showType=='hour':
                            
                            for h in range(24):
                                hour_str = '0'*(2-len(str(h))) + str(h)
                                if hour_str in groupMsg.keys():
                                    count = len(groupMsg[hour_str])
                                else:
                                    count = 0
                                total+=count
                                ws.write(i+h,j,count)
                        logging.info( 'stat : '+group+' '+ day+' ' + str(rssi)+' '+str(total))
                    i=i+incr+1
        if workBook==None:
            wb.save(xfile) 
    
    
    def export_to_excel_by_group(self,xfile='../report/店铺数据核对_customer_testing.xls',st='',et='',min_rssi=-90,max_rssi=0,walkby_min=1,walkby_max=2,comp='',groups=[],show='customer',type='stat',order='time',showTypeList=['day','hour'],opening=None):
        if os.path.exists(xfile):
            rb = xlrd.open_workbook(xfile)
            wb = copy(rb)
            sheet_names = rb.sheet_names()
        else:
            wb = xlwt.Workbook()
            sheet_names = []
        if show=='customer':
            for walkby in range(walkby_min,walkby_max) +[walkby_max]:
                
                rssiMsgList = self.stat_customer_by_hour(st=st,et=et,min_rssi=min_rssi,max_rssi=max_rssi,walkby=walkby*60,comp=comp,groups=groups,show=show,type=type,order=order,showTypeList=showTypeList,opening=opening)
                self.export_to_excel(rssiMsgList,workBook=wb,xfile=xfile,min_rssi=min_rssi,max_rssi=max_rssi,walkby=walkby*60,show=show)
        else:
            walkby = walkby_min
            rssiMsgList = self.stat_customer_by_hour(st=st,et=et,min_rssi=min_rssi,max_rssi=max_rssi,walkby=walkby*60,comp=comp,groups=groups,show=show,type=type,order=order,showTypeList=showTypeList,opening=opening)
            self.export_to_excel(rssiMsgList,workBook=wb,xfile=xfile,min_rssi=min_rssi,max_rssi=max_rssi,walkby=walkby*60,show=show)
        wb.save(xfile)

    
if __name__ == '__main__':
    import commands,os,re
    
    